package io.ukoko.controller;

import io.ukoko.dto.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CrossOrigin    //跨域
@RestController
public class FileController {


    /**
     * 文件上传
     */
    @PostMapping(value = "/uploadFile")
    public Result uploadFile(MultipartFile file,HttpServletRequest request) throws IOException {

        //获取文件名称
        String filename = file.getOriginalFilename();
        //获取文件格式
        String sub = filename.substring(filename.lastIndexOf("."), filename.length());
        //重新命名
        String newFileName = UUID.randomUUID().toString();
        //新文件名
        filename = newFileName+sub;


        //获取项目运行的真实地址
        String realPath = request.getServletContext().getRealPath("/pic");
        File f = new File(realPath);
        if(!f.exists()){
            f.mkdirs();
        }
        System.out.println("真实地址"+f);
        //将图片保存到此地址
        file.transferTo(new File(f+"/"+filename));

        //服务器地址
        String bookUrl="/pic/"+filename;
        //本地的真实地址
        String bookAddress=f+"/"+filename;

        Map<String,String> map = new HashMap<>();
        map.put("bookUrl",bookUrl);
        map.put("bookAddress",bookAddress);
        return Result.ok(map);
    }

}
